import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter_member/widget/balance_item.dart';
import 'package:flutter_member/widget/custom_appbar.dart';
import 'package:flutter_member/widget/loading_dialog.dart';
import 'package:flutter_member/widget/no_data.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:collection/collection.dart';

/*
 * 會員積分頁面
 */

class MemberShipPage extends StatefulWidget {
  @override
  _MemberShipPageState createState() => _MemberShipPageState();
}

class _MemberShipPageState extends State<MemberShipPage> {

  /// 先使用 list存储，在转换 map
  List <dynamic> listBalance= [];
  /// 第一次余额记录，转换年份
  Map mapData={};
  // 第二次余额记录，转换月份
  Map mapMember={};
  // 一次加载5条数据
  int loadData = 5;
  // 加载中
  bool _loading =true;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getMemberBalance();

  }
  ///查询积分记录
  Future<void> getMemberBalance() async {
    final ParseUser user = await ParseUser.currentUser();
    var queryMemStaLog =
    QueryBuilder<ParseObject>(ParseObject('MemberStatistics'))
      ..whereEqualTo("member", user.get("member"));
    queryMemStaLog.setLimit(loadData);
    var response = await queryMemStaLog.query();
    if (response.success && response.results != null) {
      mapData.clear();
      mapMember.clear();
      listBalance.clear();
      setState(() {
        _loading=false;
        listBalance= response.results.map((e) => {
          "objectId" : e["objectId"],
          "remark" : "remark",
          "year" : formatDate(e["date"],[yyyy]),
          "month" : formatDate(e['date'], [mm]),
          "date" : e['date'],
          "value" : e["value"],
          "type" : e["type"],
          "createdAt" : e["createdAt"]
        }).toList();
        mapData = groupBy(listBalance,(obj)=>obj['year']);
        mapMember=mapData.map((key, value) {
          return MapEntry(key,groupBy(value,(obj)=>obj['month']));
        });
      });
    }else{
      setState(() {
        _loading=false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return CustomAppBar(
      title: '會員積分',
      hight: 155,
      upperColor: 0xff2D7FC7,
      lowerColor: 0xffE5EEF6,
      childLowerTitle: _balanceWidget(),
      body: _bodyWidget()
    );
  }

  Widget _bodyWidget(){
    if(_loading==true){
      return CLoadingDialog(text: "加载中",);
    }else if(mapMember.length!=0){
      return BalanceItem(
        mapDta: mapMember,
        refresh: ()async{
          loadData=5;
          getMemberBalance();
        },
        load: ()async{
          loadData+=5;
          getMemberBalance();
        },
      );
    }else{
      return NoDataWidget();
    }
  }
  // 積分顯示組件
  Widget _balanceWidget(){
    return Container(
      margin: EdgeInsets.only(top: 10),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.only(bottomRight: Radius.circular(25),bottomLeft: Radius.circular(25))
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Container(
              child: Column(
                children: <Widget>[
                  Text(
                    "999",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: ScreenUtil().setSp(52),
                      fontWeight: FontWeight.w500
                    ),
                  ),
                ],
              )
          ),
          Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Text('分',style: TextStyle(color: Colors.white,fontSize: ScreenUtil().setSp(32)),),
              ],
            ),
          )
        ],
      ),
    );
  }
}
